import md5 from "blueimp-md5";
import { encryption } from "./encryption";

type PostRequestBody<T> = {
  appId: string;
  sign: string;
  time: number;
  bizContent: T;
};
export function dataEncryption<T extends Record<string, any>>(
  appId: string,
  appKey: string,
  token: string,
  data?: T
) {
  if (!appId || !appKey) {
    throw new Error("请传入数据加密的 appId 和 appKey");
  }
  const kktoken = token ? `&token=${token}` : "";
  const startStr = encryption(data);
  const time = parseInt(String(new Date().getTime() / 1000), 10);
  const startStrValue = startStr ? `${startStr}&` : "";
  const str = `${startStrValue}appId=${appId}&appKey=${appKey}&time=${time}${kktoken}`;

  const sign = md5(str).toLowerCase();

  return {
    appId,
    sign,
    time,
    bizContent: data || {},
  };
}

/**
 * @description: kkweb post 请求加签加密
 * @beta
 * @param appId appId
 * @param appKey appKey
 * @return {function} 按照指定规则生成的请求体
 * @example
 * ```js
 * const postBodyEncryption = createEncryption("appId", "appKey")
 * const newBody = postBodyEncryption("token", {foo: 'bar'})
 * => {
      appId: 'appId',
      sign: 'ef5020eed24b9e587a0ba5a7a6ff1045',
      time: 1685083253,
      bizContent: {foo: 'bar'},
    }
 * ```
 */
function createEncryption(appId: string, appKey: string) {
  return (token: string, data?: any) =>
    dataEncryption(appId, appKey, token, data);
}

export default createEncryption;
